var parent_uri = null;
function ParentURI() {
    if (parent_uri == null) {
	var parent_url = "";
	if (gadgets.util.getUrlParameters().hasOwnProperty("parent")) {
	    parent_url = gadgets.util.getUrlParameters()["parent"];
	}
	parent_uri = parseUri(parent_url);
    }
    return parent_uri;
}

function ParentParam(name) {
    var parent_uri = ParentURI();
    if (!parent_uri.queryKey.hasOwnProperty(name)) return null;
    return parent_uri.queryKey[name];
}

// Note: this must match LibraryManager::clean_label()
function clean_label(label) {
    var clean = label.toLowerCase();
    clean = clean.replace(new RegExp(/[ \/]/g), '-');
    clean = clean.replace(new RegExp(/[)(]/g), '');
    return clean;
}

function LabelSorter(a, b) {
    return a[1].toLocaleLowerCase().localeCompare(b[1].toLocaleLowerCase());
}

function SetBase() {
    var base = document.getElementsByTagName('base')[0];
    if (!base) {
	base = document.createElement('base');
	document.getElementsByTagName("head")[0].appendChild(base);
    }
    var base_uri = CalculateSiteURL("/");
    base.href = base_uri;
}

var site_url_base = null;
function CalculateSiteURL(path) {
    if (site_url_base == null) {
	var parent_uri = ParentURI();
	if (parent_uri.host == 'sites.google.com' && 
	    parent_uri.path.substr(0,3) == '/a/') {
	    var domain_len = parent_uri.path.indexOf('/', 3) - 3;
	    var site_len = parent_uri.path.indexOf('/', domain_len + 4) -
		domain_len - 4;
	    site_url_base = parent_uri.protocol + '://sites.google.com/a/' +
		parent_uri.path.substr(3, domain_len) + '/' +
		parent_uri.path.substr(domain_len + 4, site_len);
	} else {
	    site_url_base = parent_uri.protocol + '://' + parent_uri.host;
	}
    }
    return site_url_base + path;
}

function CalculateBackendURL(path) {
    var gadget_url = _args()["url"];
    var offset = gadget_url.search("/gadgets/");
    return gadget_url.substr(0, offset) + path;
}

function LoadGadgetFile(element, onload) {
    if (onload) element.onload = onload;
    document.body.appendChild(element);
}

function LoadJavascript(file, onload) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = CalculateBackendURL("/gadgets/" + file);
    LoadGadgetFile(script, onload);
}

function LoadCSS(file) {
    var style = document.createElement("link");
    style.rel = "stylesheet";
    style.type = "text/css";
    // style.href = CalculateBackendURL("/gadgets/" + file);
    style.href = "http://veronicaerb.com/rec/" + file;
    LoadGadgetFile(style);
}

function RequestLibraryData(query, callback) {
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] =
	gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
    var url = CalculateBackendURL("/library/" + query);
    var inner_callback = function(obj) {
	callback(obj.data.results, obj.data.q);
    }
    gadgets.io.makeRequest(url, inner_callback, params);
}

function CalculateFileType(result) {
    if (result.url.indexOf(".doc") != -1) return "doc";
    if (result.url.indexOf(".docx") != -1) return "docx";
    if (result.url.indexOf(".pdf") != -1) return 'pdf';
    if (result.url.indexOf("http://www.youtube.com/") != -1) return 'video';
    for (i in result.labels) {
	if (result.labels[i][0] == 'storage:site-external') return 'link';
    }
    return 'unknown';
}

function FindResourceType(result) {
    for (i in result.labels) {
	if (result.labels[i][0].substr(0, 5) == "type:") {
	    return result.labels[i][1];
	}
    }
    return "<em>unknown resource type</em>";
}

function RenderLibraryListing(metadata, back_id) {
    var doc_url = CalculateSiteURL(
	"/library/resource?id=" + metadata.id + "&back=home");
    var year = metadata.year ? metadata.year : "<em>unknown</em>";
    return '<div class="result article"><h3><a href="' + doc_url +
	'" target="_top">' + metadata.title + "</a></h3>\n" +
	"<ul><li class=\"type_" + CalculateFileType(metadata) +
	"\"><a href=\"" + doc_url +
	'" target="_top">' + FindResourceType(metadata) +
	"</a></li></ul><p>" + metadata.description + "</p>\n" +
	"<dl><dt>Year:</dt><dd>" + year + "</dd>\n" +
	"<dt>Source(s):</dt><dd>" + metadata.sources.join(', ') +
	"</dd></dl>\n"
}

function ProcessLibraryDocuments(target, results, back_id) {
    var html = "";
    for (var i in results) {
	html += RenderLibraryListing(results[i], back_id);
    }
    if (results.length == 0) {
	html = "<p><em>No documents found.</em></p>"
    }
    document.getElementById(target).innerHTML = html;
    gadgets.window.adjustHeight();
}

function XMLChildrenByNodeName(parent, node_name) {
    var children = [];
    var list = parent.childNodes;
    for (var i = 0; i < list.length; ++i) {
	var child = list.item(i);
	if (child.nodeName != node_name) continue;
	children.push(child);
    }
    return children;
}

function TextifyAge(now, then) {
    var seconds = (now.getTime() - then.getTime()) / 1000;
    if (seconds < 60) return Math.floor(seconds) + ' seconds ago';
    if (seconds < 3600) return Math.floor(seconds/60) + ' minutes ago';
    if (seconds < 86400) return Math.floor(seconds/3600) + ' hours ago';
    if (seconds < 604800) return Math.floor(seconds/86400) + ' days ago';
    return then.toLocaleDateString();
}

function RequestUserData(callback) {
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] =
	gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
    var url = CalculateBackendURL(
	'/users/user_info?requestor=' +
	    gadgets.util.getUrlParameters()["parent"]);
    gadgets.io.makeRequest(url, callback, params);
}

function FinishSignIn() {
    var old_href = window.opener.location.href;
    window.opener.location.href = 'http://www.educationcommons.rw/test';
    window.opener.location.href = window.opener.location.href;
    window.close();
}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
    var o   = parseUri.options,
	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
	uri = {},
	i   = 14;
	
	while (i--) uri[o.key[i]] = m[i] || "";
	
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	    });
	
	return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
	name:   "queryKey",
	parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
	strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
	loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};
